<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input :placeholder="filterTypeSelect === 'terminalName' ? '请输入设备名称进行查询' : '请输入设备编号进行查询'" v-model="filterText" class="input-with-select" size="mini">
            <el-select v-model="filterTypeSelect" slot="prepend" placeholder="请选择" style="width: 100px;">
              <el-option label="设备名称" value="terminalName"></el-option>
              <el-option label="设备编号" value="termianlId"></el-option>
            </el-select>
            <!--            <el-button slot="append" icon="el-icon-search" style="width: 40px;"></el-button>-->
          </el-input>
          <div style="max-height:96%;min-height: 96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :default-expanded-keys="defaultExpandedKeys"
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              highlight-current
              v-loading="treeLoading"
              show-checkbox
              @check="onCheck"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span class="iconfont icon-dabiao icon-padding"
                        v-if="data.deviceType !== 0 && data.deviceType !== 1 && data.deviceType !== 2"></span>
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 5px 10px 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-col class="form_col">
              <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                       :label-width="labelWidth">
                <div id="searchFilter">
                  <el-form-item label="日期" prop="dateValue" :rules="[{ required: true, message: '时间不能为空'}]">
                    <el-date-picker
                      v-model="queryParams.dateValue"
                      type="daterange"
                      value-format="yyyy-MM-dd"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      @change="handleDateChange"
                      style="width: 100%"
                    >
                    </el-date-picker>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>
            <el-col class="form_query">
              <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text" size="mini">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
              </el-button>
              <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
              <el-button @click="resetQuery" size="mini">重置</el-button>
<!--              <RightDropdown :columns="columns" :showSearch.sync="showSearch" :queryVisible="false" :exportVisible="false" class="ml10"></RightDropdown>-->
            </el-col>
          </el-row>

<!--          <el-row :gutter="10" class="mb8">-->

<!--          </el-row>-->

          <el-table ref="table" border v-loading="loading" :data="dataList" size="mini" :height="getAvailableHeight">
            <template v-for="(item, index) in columns">
              <el-table-column :label="item.label" :prop="item.prop" :show-overflow-tooltip="true" align="center">
                <template v-if="item.children">
                  <template v-for="(item1, index1) in item.children">
                    <el-table-column :label="item1.label" :show-overflow-tooltip="true" align="center"
                                     :prop="item1.prop"></el-table-column>
                  </template>
                </template>
              </el-table-column>
            </template>
          </el-table>
<!--          <pagination :total="total"-->
<!--                      :page.sync="queryParams.pageNum"-->
<!--                      :limit.sync="queryParams.pageSize"-->
<!--                      @pagination="handleQuery"/>-->
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listTerminalsDbTree } from "@/api/record/terminalsdb";
import { getMiniFlowComparison, listAreaTree } from '@/api/datastatistics/terminals/dosageStatics.js'
import moment from "moment";

export default {
  name: "NightStreamReport",
  dicts: ['sign_platform'],
  data() {
    return {
      filterTypeSelect: 'terminalName',
      dataObj: {},
      resultData: [],
      columnsLabels: [],
      defaultExpandedKeys: [],
      filterText: '',
      // 区域树选项
      sheetsTreeList: [],
      treeLoading: false,
      screenHeight: null,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      maxShow: 4,
      labelWidth: '60px',
      // 列信息
      columns: [],
      // 默认排序
      defaultSort: {prop: 'readDate', order: 'descending'},
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // total: 0,
      // 表格数据
      dataList: [],
      defaultProps: {
        children: "children",
        label: "label",
        // isLeaf: "isLeaf",
      },
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 20,
        locationNb: '',
        dateValue: [moment(new Date()).subtract(15, 'days').format('YYYY-MM-DD'),moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')],
        terminalId: '',
        beginDate: moment(new Date()).subtract(15, 'days').format('YYYY-MM-DD'),
        endDate: moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD'),
      },
      // 复选框数据
      checkInfo: {
        length: 0, // 选中个数
        info: [], // 选中的数据
        checkedKeys: [],
      },
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 180
    },
  },
  mounted() {
    this.getTreeList();
    this.$message.warning('请选择终端进行查询！')
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },

  watch: {
    // 根据名称筛选区域树
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    handleScroll() {
      this.$nextTick(() => {
        window.setTimeout(() => {
          this.$refs.table.doLayout()
        }, 100)
      })
    },
    // 监听时间变化
    handleDateChange(value) {
      this.queryParams.beginDate = value[0]
      this.queryParams.endDate = value[1]
    },
    onCheck(data, node) {
      this.checkInfo.info = []
      let checkData = node.checkedNodes
      checkData = checkData.filter((item) => item.deviceType === 3);
      if (checkData.length === 0) {
        this.columns = []
      } else if (checkData.length > 30) {
        this.checkInfo.info = checkData
        this.$message.warning("最多选择三十台终端")
      } else {
        this.checkInfo.info = checkData
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if(!value){
        return true
      }else{
        if(this.filterTypeSelect === 'terminalName'){
          return data.label.indexOf(value) !== -1;
        }else {
          if(data.deviceType === 3){
            return data.locationNb.indexOf(value) !== -1;
          }
        }
      }
    },
    /** 查询树 */
    getTreeList() {
      this.treeLoading = true
      this.sheetsTreeList = []
      listAreaTree().then(res => {
        if (res.code === 200) {
          if(res.data.id === 0) {
            this.sheetsTreeList.push(...res.data.children) // 没有返回termianlId
          }else {
            this.sheetsTreeList.push(res.data)
          }
          if(this.defaultExpandedKeys.length){
            this.defaultExpandedKeys = [this.sheetsTreeList[0].id]
          }
          // this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
          this.treeLoading = false
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.dataList = []
      this.queryParams.locationNb = ''
      this.loading = true
      if (this.checkInfo.info.length === 0) {
        this.columns = [{
          label: '时间',
          prop: 'date',
          width: null,
          align: 'center',
        }]
        this.$message.warning('最少选择一台终端！');
        this.loading = false
      } else if (this.checkInfo.info.length > 30) {
        this.columns = [{
          label: '时间',
          prop: 'date',
          width: null,
          align: 'center',
        }]
        this.$message.warning('最多选择三十台终端！');
        this.loading = false
      } else {
        this.$refs['queryForm'].validate((valid) => {
          if(valid){
            this.columns = [{
              label: '时间',
              prop: 'date',
              width: null,
              align: 'center',
            }]
            this.checkInfo.info.forEach(item => {
              let columns = {
                label: item.label,
                width: 450,
                align: 'center',
                children: [{
                  label: '夜间最小流量(m³/h)',
                  width: 160,
                  prop: `miniFlow_${item.id}`,
                  align: 'center',
                }, {
                  label: '瞬时流量占比(%)',
                  width: 160,
                  prop: `rate_${item.id}`,
                  align: 'center',
                }, {
                  label: '出现时间',
                  width: 160,
                  prop: `appearanceTime_${item.id}`,
                  align: 'center',
                }]
              }
              this.columns.push(columns)
            })
            this.checkInfo.info.map((item, index) => {
              this.queryParams.locationNb += item.locationNb + ','
            })
            this.queryParams.locationNb = this.queryParams.locationNb.substr(0, this.queryParams.locationNb.length - 1)
            getMiniFlowComparison(this.queryParams)
              .then(this.renderReport)
              .catch(() => { this.loading = false })
          }
        })
      }
    },
    renderReport(res) {
      if (res.code === 200) {
        this.resultData = []
        let data = res.data
        for (let i = 0; i < data.length; i++) {
          this.dataObj = {}
          for (let j = 0; j < data[i].length; j++) {
            let obj = {
              date: data[i][j].date,
              ['miniFlow_' + data[i][j].terminalId]: data[i][j].miniFlow != null ? data[i][j].miniFlow : null,
              ['rate_' + data[i][j].terminalId]: data[i][j].rate != null ? data[i][j].rate + '%' : null,
              ['appearanceTime_' + data[i][j].terminalId]: data[i][j].appearanceTime != null ? data[i][j].appearanceTime : null,
            }
            this.dataObj = Object.assign(this.dataObj, obj)
          }
          this.resultData.push(this.dataObj)
        }
        this.dataList = this.resultData
        this.handleScroll()
        this.loading = false

      } else {
        this.dataList = []
        this.loading = false;
        return false
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetChecked()
      this.queryParams = {
        // pageNum: 1,
        // pageSize: 20,
        locationNb:'',
        terminalId: '',
        dateValue: [moment(new Date()).subtract(15, 'days').format('YYYY-MM-DD'),moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')],
        beginDate: moment(new Date()).subtract(15, 'days').format('YYYY-MM-DD'),
        endDate: moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD'),
      }
      this.tip()
    },
    // 清空选中的设备
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    // 提示信息
    tip() {
      this.$message.warning('请选择终端进行查看')
    },
  }
};
</script>
<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node {
    width: fit-content;
  }

  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }
}

//.form_col {
//  width: 80%;
//
//  ::v-deep .el-form {
//    width: 100%;
//  }
//
//  ::v-deep .el-form-item {
//    width: 15%;
//  }
//}
//
//.form_query {
//  width: 20%;
//  text-align: right;
//}
//::v-deep .el-table__body-wrapper::-webkit-scrollbar {
//  // width: 20px; /* 纵向滚动条 */
//  height: 5px; /* 横向滚动条 必写 */
//  position: absolute;
//  bottom: 0;
//}
///* 设置滚动条样式 */
//::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
//  //设置滚动条哑颜色，根据自己选择设置
//    // background-color: #dde;
//  border-radius: 5px;
//}
</style>
